package org.niugang.coding.conf;

import com.alibaba.fastjson.JSON;
import org.niugang.coding.exception.CustomException;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义登录失败
 *
 * @author Created by niugang on 2019/1/25/20:29
 */
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {


        httpServletResponse.setContentType("application/json;charset=utf-8");
        CustomException respBean = null;
        if (e instanceof BadCredentialsException ||
                e instanceof UsernameNotFoundException) {
            respBean = CustomException.builder().message("账户名或者密码输入错误").status(HttpStatus.UNAUTHORIZED.value()).path(httpServletRequest.getServletPath().toString()).timestamp(System.currentTimeMillis()).build();

        } else {
            respBean = CustomException.builder().message("登录失败").status(HttpStatus.UNAUTHORIZED.value()).path(httpServletRequest.getServletPath().toString()).timestamp(System.currentTimeMillis()).build();

        }
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        PrintWriter out = httpServletResponse.getWriter();
        out.write(JSON.toJSONString(respBean));
        out.flush();
        out.close();
    }
}
